import { describe, bench, beforeAll, afterAll } from 'vitest';
import { render, cleanup } from '@testing-library/react';
import React from 'react';

// 模拟组件
const SimpleComponent = () => <div>Hello World</div>;

const ComplexComponent = () => (
  <div>
    {Array.from({ length: 100 }, (_, i) => (
      <div key={i}>
        <span>Item {i}</span>
        <button onClick={() => console.log(i)}>Click {i}</button>
      </div>
    ))}
  </div>
);

// 模拟数据处理函数
function processLargeArray(size: number) {
  const arr = Array.from({ length: size }, (_, i) => i);
  return arr
    .filter(x => x % 2 === 0)
    .map(x => x * 2)
    .reduce((sum, x) => sum + x, 0);
}

function fibonacci(n: number): number {
  if (n <= 1) return n;
  return fibonacci(n - 1) + fibonacci(n - 2);
}

function fibonacciMemo(n: number, memo: Map<number, number> = new Map()): number {
  if (n <= 1) return n;
  if (memo.has(n)) return memo.get(n)!;
  
  const result = fibonacciMemo(n - 1, memo) + fibonacciMemo(n - 2, memo);
  memo.set(n, result);
  return result;
}

// 模拟 API 调用
async function mockApiCall(delay: number = 100) {
  return new Promise(resolve => setTimeout(resolve, delay));
}

// 模拟状态管理操作
class SimpleStore {
  private state: Record<string, any> = {};
  private listeners: Set<() => void> = new Set();

  setState(updates: Record<string, any>) {
    this.state = { ...this.state, ...updates };
    this.listeners.forEach(listener => listener());
  }

  getState() {
    return this.state;
  }

  subscribe(listener: () => void) {
    this.listeners.add(listener);
    return () => this.listeners.delete(listener);
  }
}

describe('React 组件渲染性能', () => {
  afterAll(() => {
    cleanup();
  });

  bench('简单组件渲染', () => {
    render(React.createElement(SimpleComponent));
  });

  bench('复杂组件渲染', () => {
    render(React.createElement(ComplexComponent));
  });

  bench('大量组件渲染', () => {
    const ManyComponents = () => (
      <div>
        {Array.from({ length: 1000 }, (_, i) => (
          <SimpleComponent key={i} />
        ))}
      </div>
    );
    render(React.createElement(ManyComponents));
  });
});

describe('数据处理性能', () => {
  bench('小数组处理 (1K)', () => {
    processLargeArray(1000);
  });

  bench('中等数组处理 (10K)', () => {
    processLargeArray(10000);
  });

  bench('大数组处理 (100K)', () => {
    processLargeArray(100000);
  });

  bench('JSON 序列化', () => {
    const data = Array.from({ length: 1000 }, (_, i) => ({
      id: i,
      name: `Item ${i}`,
      value: Math.random(),
      nested: {
        prop1: `value${i}`,
        prop2: i * 2,
      }
    }));
    JSON.stringify(data);
  });

  bench('JSON 反序列化', () => {
    const jsonString = JSON.stringify(
      Array.from({ length: 1000 }, (_, i) => ({
        id: i,
        name: `Item ${i}`,
        value: Math.random(),
      }))
    );
    JSON.parse(jsonString);
  });
});

describe('算法性能对比', () => {
  bench('斐波那契递归 (n=30)', () => {
    fibonacci(30);
  });

  bench('斐波那契记忆化 (n=30)', () => {
    fibonacciMemo(30);
  });

  bench('数组查找 - indexOf', () => {
    const arr = Array.from({ length: 10000 }, (_, i) => i);
    arr.indexOf(9999);
  });

  bench('数组查找 - includes', () => {
    const arr = Array.from({ length: 10000 }, (_, i) => i);
    arr.includes(9999);
  });

  bench('数组查找 - Set.has', () => {
    const set = new Set(Array.from({ length: 10000 }, (_, i) => i));
    set.has(9999);
  });

  bench('对象属性访问', () => {
    const obj = Object.fromEntries(
      Array.from({ length: 1000 }, (_, i) => [`key${i}`, `value${i}`])
    );
    for (let i = 0; i < 1000; i++) {
      obj[`key${i}`];
    }
  });

  bench('Map 访问', () => {
    const map = new Map(
      Array.from({ length: 1000 }, (_, i) => [`key${i}`, `value${i}`])
    );
    for (let i = 0; i < 1000; i++) {
      map.get(`key${i}`);
    }
  });
});

describe('异步操作性能', () => {
  bench('Promise.all 并发', async () => {
    const promises = Array.from({ length: 10 }, () => mockApiCall(10));
    await Promise.all(promises);
  });

  bench('串行 await', async () => {
    for (let i = 0; i < 10; i++) {
      await mockApiCall(10);
    }
  });

  bench('Promise 创建', () => {
    Array.from({ length: 1000 }, () => new Promise(resolve => resolve(true)));
  });
});

describe('状态管理性能', () => {
  let store: SimpleStore;

  beforeAll(() => {
    store = new SimpleStore();
  });

  bench('状态更新', () => {
    store.setState({ counter: Math.random() });
  });

  bench('状态读取', () => {
    store.getState();
  });

  bench('订阅管理', () => {
    const unsubscribe = store.subscribe(() => {});
    unsubscribe();
  });

  bench('大量状态更新', () => {
    for (let i = 0; i < 100; i++) {
      store.setState({ [`key${i}`]: i });
    }
  });
});

describe('DOM 操作性能', () => {
  bench('createElement', () => {
    Array.from({ length: 100 }, () => {
      const div = document.createElement('div');
      div.textContent = 'Hello World';
      return div;
    });
  });

  bench('innerHTML', () => {
    const container = document.createElement('div');
    container.innerHTML = Array.from({ length: 100 }, (_, i) => 
      `<div>Item ${i}</div>`
    ).join('');
  });

  bench('DocumentFragment', () => {
    const fragment = document.createDocumentFragment();
    Array.from({ length: 100 }, (_, i) => {
      const div = document.createElement('div');
      div.textContent = `Item ${i}`;
      fragment.appendChild(div);
    });
  });
});

describe('字符串操作性能', () => {
  const longString = 'a'.repeat(10000);
  const shortStrings = Array.from({ length: 1000 }, (_, i) => `string${i}`);

  bench('字符串连接 - +', () => {
    let result = '';
    for (const str of shortStrings) {
      result += str;
    }
  });

  bench('字符串连接 - join', () => {
    shortStrings.join('');
  });

  bench('字符串搜索 - indexOf', () => {
    longString.indexOf('aaaa');
  });

  bench('字符串搜索 - includes', () => {
    longString.includes('aaaa');
  });

  bench('正则表达式匹配', () => {
    /a{4}/.test(longString);
  });

  bench('字符串替换', () => {
    longString.replace(/a/g, 'b');
  });
});

describe('内存使用模式', () => {
  bench('数组创建和销毁', () => {
    const arrays = Array.from({ length: 100 }, () => 
      Array.from({ length: 1000 }, (_, i) => i)
    );
    // 数组会在函数结束时被垃圾回收
  });

  bench('对象创建和销毁', () => {
    const objects = Array.from({ length: 1000 }, (_, i) => ({
      id: i,
      data: Array.from({ length: 100 }, (_, j) => j),
    }));
    // 对象会在函数结束时被垃圾回收
  });

  bench('WeakMap 操作', () => {
    const weakMap = new WeakMap();
    const objects = Array.from({ length: 100 }, () => ({}));
    
    objects.forEach((obj, i) => {
      weakMap.set(obj, i);
    });
    
    objects.forEach(obj => {
      weakMap.get(obj);
    });
  });
});
